//
//  ResultSearchDirectoryViewController.m
//  HandyDialer
//
//	Developed by Team Synergy
//  Created by Jordan Tseng on 10/29/11.
//  Coders: Jacky Li and Jordan Tseng 
//  Graphic Designer: Derek Fong
//  Developers: Brad Lisson, Derek Fong, Jacky Li, Jeremy Gangoso, Jordan Tseng
//  Copyright HandyDialer 2011. All rights reserved.
//


#import "ResultSearchDirectoryViewController.h"




@implementation ResultSearchDirectoryViewController
@synthesize  highlightArea;
@synthesize backgroundArea;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
		firstTime = true;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark - View lifecycle


- (void)dealloc {
	[highlightArea release];
    [super dealloc];
}

- (void)viewDidLoad {
    
    counter = 0;
    defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_results_default.png"]]];
	[self parseHTML];
	[super viewDidLoad];
	 
}

- (void)viewDidAppear:(BOOL)animated
{
    defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_results_default.png"]]];

	if (uniTimer == nil)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(optionChange) userInfo:nil repeats:YES];
	[super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[uniTimer invalidate];
	uniTimer = nil;
	[super viewDidDisappear:animated];
}

- (IBAction)switchView:(id)sender{
    // Does nothing if counter is 0
	if(counter !=0)
	{
        // Go back to search screen
		if(counter == 1)
        {
            counter = 0;
			[self dismissModalViewControllerAnimated:NO];
        }
        // Go back to main menu
		else if (counter == 2)
        {
            counter = 0;
			[self returnToView:@"MenuView":self];
        }
	}
}

- (void)returnToView:(NSString *)viewName:(UIViewController *)previousView
{
	// recursively traverse through parent ViewControllers to find desired view
	previousView = [previousView presentingViewController];
	NSLog(@"%@", previousView.nibName);
	if (previousView.nibName == viewName)
	{
		[previousView dismissModalViewControllerAnimated:NO];
	}
	else
	{
		[self returnToView:(viewName):(previousView)];
	}
}

- (void)highlightChange:(NSString *)picture
{
    UIImage *image = [UIImage imageNamed: picture];
    [highlightArea setImage:image];
	
}

- (void)parseHTML
{
	enum ResultType {NO_RESULT,PERSON};
    // Declaration of DataStorage Singleton 
	DataStorage *data = [DataStorage sharedData];
	NSString *searchNumber = [data getReverseNumber];
	NSLog(@"%@", searchNumber);
	
	NSError *error = nil;
    
    // Website url
	NSString *urlString = @"http://mytelus.canada411.ca/search/?stype=re&what=";
	urlString = [urlString stringByAppendingFormat:@"%@",searchNumber];

	NSURL *url = [NSURL URLWithString:urlString];
	
	NSString *html = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error: &error];
	
    // Parse HTML code
	HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];
	 
	if (error) 
    {
        NSLog(@"Error: %@", error);
        return;
	}
	 
	 
	HTMLNode *bodyNode = [parser body];
	
	enum ResultType result = NO_RESULT;
	
	NSArray *divNodes = [bodyNode findChildTags:@"div"];
	
	HTMLNode *resultNode;
	
    // Decides between valid result or no result
	for (HTMLNode *divNode in divNodes) 
	{
		if ([[divNode getAttributeNamed:@"id"] isEqualToString:@"contact"])
		{
			result = PERSON;
			resultNode = divNode;

			NSLog(@"person page");
			break;
		}
	}
	
    // Parse result to appropriate fields
	switch (result)
	{
		case NO_RESULT:
		{
			searchResult.text = [NSString stringWithFormat:@"%@\nReturned no results!",searchNumber];
			break;
		}
		case PERSON:
		{
			NSString *personName = nil, *personNumber = nil, *personAddress = nil, *personLocation = nil, *personPostalCode = nil;
			personName = [[resultNode findChildTag:@"h1"] contents];
			NSArray *resultDivNodes = [resultNode findChildTags:@"div"];
			for (HTMLNode *resultDivNode in resultDivNodes)
			{
				if ([[resultDivNode getAttributeNamed:@"class"] isEqualToString:@"c411ListingDetails"])
				{
					personNumber = [[resultDivNode findChildTag:@"span"] contents];
				}
				else if ([[resultDivNode getAttributeNamed:@"class"] isEqualToString:@"c411ListingAddress"])
				{
					personAddress = [resultDivNode.firstChild contents];
					if ([[resultDivNode findChildTag:@"span"] getAttributeNamed:@"class"] == nil)
					{
						personAddress = [[resultDivNode findChildTag:@"span"] contents];
					}
				}
				else if ([[resultDivNode getAttributeNamed:@"class"] isEqualToString:@"adr"])
				{
					NSArray *spanDivAdrNodes = [resultDivNode findChildTags:@"span"];
					for (HTMLNode *spanDivAdrNode in spanDivAdrNodes)
					{
						if ([[spanDivAdrNode getAttributeNamed:@"class"] isEqualToString:@"locality"])
						{
							personLocation = [spanDivAdrNode contents];
						}
						else if ([[spanDivAdrNode getAttributeNamed:@"class"] isEqualToString:@"region"])
						{
							personLocation = [personLocation stringByAppendingFormat:@", %@",[spanDivAdrNode contents]];
						}
						else if ([[spanDivAdrNode getAttributeNamed:@"class"] isEqualToString:@"postal-code"])
						{
							personPostalCode = [spanDivAdrNode contents];
						}
					}
				}
			}
            // Append person info into searchResult label
			if (personName != nil)
			{
				NSString *personInfo = personName;
				if(personNumber != nil)
				{
					personInfo = [personInfo stringByAppendingFormat:@"\n%@",personNumber];
				}
				if (personAddress != nil)
				{
					personInfo = [personInfo stringByAppendingFormat:@"\n%@",personAddress];
				}
				if (personLocation != nil)
				{
					personInfo = [personInfo stringByAppendingFormat:@"\n%@",personLocation];
				}
				if (personPostalCode != nil)
				{
					personInfo = [personInfo stringByAppendingFormat:@"\n%@",personPostalCode];
				}
				searchResult.text =  personInfo;
			}
			else
			{
				searchResult.text = @"No Results!";
			}
			break;
		}


	}
	[parser release];
}

- (void)optionChange 
{
    // Reset counter
    if (counter == 2)
    {
        counter = 0;
    }
	counter += 1;
    
	NSString *next = highlightColor;
    next = [next stringByAppendingString:@"_results_"];  
	next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", counter]];
	next = [next stringByAppendingString:@".png"];
	[self highlightChange:next];
		
	
}
	
@end
